package cn.wolfcode.crm.service.imp;


import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.*;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IStockOutcomeBillService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;


@Service
public class StockOutcomeBillServiceImpl implements IStockOutcomeBillService {


    @Autowired
    private StockOutComeBillMapper stockOutComeBillMapper;

    @Autowired
    private StockOutcomeBillItemMapper stockOutcomeBillItemMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private GiftMapper giftMapper;



    public void saveOrUpdate(StockOutComeBill entity) {
        if (Optional.ofNullable(entity.getId()).isPresent()) {
            // 有ID,更新
            update(entity);
        } else {
            insertBill(entity);
        }
    }




    // 更新订单
    private void update(StockOutComeBill entity) {

        // 判断旧数据的状态必须是未审核
        StockOutComeBill old = stockOutComeBillMapper.selectByPrimaryKey(entity.getId());

    }

    // 新增订单
    private void insertBill(StockOutComeBill entity) {
        // 明细数量判断
        if (entity.getItems().size() == 0) {
            throw new RuntimeException("至少需要保存一条明细!");
        }

        // 先重置单据录入人/录入时间
        Employee user = UserContext.getCurrentUser();
        entity.setInputUser(user);
        entity.setInputTime(new Date());

        // 重新计算每个明细的数量跟价格
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (StockOutcomeBillItem item : entity.getItems()) {

            // 获取商品并获取库存
            Product product = productMapper.selectByPrimaryKey(item.getProduct().getId());
            Stock stock = stockMapper.selectByProductId(product.getId());
            if (!Optional.ofNullable(stock).isPresent()) {
                // 没有库存,抛异常
                throw new RuntimeException(product.getProductName() + "没有库存!");
            }

            if (item.getNumber().compareTo(stock.getNumber()) > 0) {
                // 要销售的数量比库存的数量大,抛异常
                throw new RuntimeException(product.getProductName() + "库存不足!");
            }

            // 更新库存数量
            stock.setNumber(stock.getNumber().subtract(item.getNumber()));
            stockMapper.updateNumber(stock);


            // 重新计算总价
            if (!entity.getOutType().equals(StockOutComeBill.GIFT)) {

            BigDecimal amount = item.getNumber().multiply(item.getSalePrice()).setScale(2,RoundingMode.HALF_UP);
            item.setAmount(amount);
            totalAmount = totalAmount.add(amount);
            }
            // 累加总量
            totalNumber = totalNumber.add(item.getNumber());
        }

        // 重新设置总量
        entity.setTotalNumber(totalNumber);
        entity.setTotalAmount(totalAmount);

        // 保存到数据库
        stockOutComeBillMapper.insert(entity);
        // 再保存明细(因为先需要订单的id)
        for (StockOutcomeBillItem item : entity.getItems()) {
            item.setBillId(entity.getId());
            stockOutcomeBillItemMapper.insert(item);
        }
    }





    public void deleteByPrimaryKey(Long id) {

    }

    public StockOutComeBill selectByPrimaryKey(Long id) {
        return null;
    }

    public List<StockOutComeBill> selectAll() {
        return null;
    }

    public PageResult query(QueryObject qo) {
        int rows = stockOutComeBillMapper.query4count(qo);
        if (rows==0) {
            return PageResult.EMPTY_RESULT;
        }
        PageResult result =  new PageResult(rows,stockOutComeBillMapper.query4list(qo));
        return result;

    }

    public void audit(Long id) {
        //获取要审核的数据
        StockOutComeBill bill = stockOutComeBillMapper.selectByPrimaryKey(id);
        if (bill.getStatus() == StockOutComeBill.AUDITED) {
            throw new RuntimeException("该订单已审核!");
        }

        for (StockOutcomeBillItem item : bill.getItems()) {

            // 获取商品并获取库存
            Product product = productMapper.selectByPrimaryKey(item.getProduct().getId());
            Stock stock = stockMapper.selectByProductId(product.getId());
            if (!Optional.ofNullable(stock).isPresent()) {
                // 没有库存,抛异常
                throw new RuntimeException(product.getProductName() + "没有库存!");
            }

            if (item.getNumber().compareTo(stock.getNumber()) > 0) {
                // 要销售的数量比库存的数量大,抛异常
                throw new RuntimeException(product.getProductName() + "库存不足!");
            }


            // 更新库存数量
            stock.setNumber(stock.getNumber().subtract(item.getNumber()));
            stockMapper.updateNumber(stock);
        }
        //所有礼品列表
        List<Gift> gifts = giftMapper.selectAll();


        //如果是礼品直接出库到礼品库
        if (bill.getOutType()== StockOutComeBill.GIFT) {


            for (StockOutcomeBillItem item : bill.getItems()) {
                //获取到礼品库的库存判断是否已经存在该商品
                //有则增加数量,无直接插入
                if (gifts.size()==0) {
                    gifts= new ArrayList<>();
                    Gift newGift = new Gift();
                    newGift.setNumber(item.getNumber());
                    newGift.setName(item.getProduct().getProductName());
                    newGift.setSn(item.getProduct().getProductSn());
                    giftMapper.insert(newGift);
                }
                for (Gift gift : gifts) {
                    if (gift.getSn()==item.getProduct().getProductSn()) {
                        //说明礼品中存在该商品 ,移动加权
                       gift.setNumber(gift.getNumber().add(item.getNumber()));
                       giftMapper.updateByPrimaryKey(gift);
                    }
                    else {
                        //说明礼品库中没有该商品 直接插入
                        Gift newGift = new Gift();
                        newGift.setNumber(item.getNumber());
                        newGift.setName(item.getProduct().getProductName());
                        newGift.setSn(item.getProduct().getProductSn());
                        giftMapper.insert(newGift);
                    }
                }



            }
        }


        bill.setStatus(StockOutComeBill.AUDITED);
        bill.setAuditTime(new Date());
        bill.setAuditor(UserContext.getCurrentUser());
        stockOutComeBillMapper.audit(bill);
    }
}
